<?php


namespace Cumulon\Service\Kernel\Http;

use GuzzleHttp\Exception\GuzzleException;
use Overtrue\Http\Support\Collection;
use Psr\Http\Message\ResponseInterface;
use Cumulon\Service\Kernel\Concerns\InteractsWithCache;
use Overtrue\Http\Client as BaseClient;
use Illuminate\Support\Facades\Cache;


class Client extends BaseClient
{
    use InteractsWithCache;
    /**
     * @var
     */
    protected $app;

    /**
     * @var array
     */
    protected static $httpConfig = [
        'base_uri' => 'http://user.api.superljq01.com',
    ];

    /**
     * Client constructor.
     * @param $app
     * @throws \Exception
     */
    public function __construct($app)
    {
        $this->app = $app;
        parent::__construct(array_merge($this->withAccessTokenMiddleware(), $this->app['config']->get('http', [])));
    }

    /**
     * @return array
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function withAccessTokenMiddleware(){
        $access_token = $this->app['request']->headers->get('Authorization');
        $access_token = $this->bearerToken($access_token);
        if(empty($access_token)){
            $access_token = $this->app['request']->query->get('token');
        }
        if ($access_token) {
            $access_token = Cache::get($access_token); //获取回调过来的token
        }else{
            $access_token = '';
        }
        return [
            'base_uri' => $this->app['config']->get('base_url',""),
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' =>'Bearer '.$access_token
            ]
        ];
    }

    /**
     * @param $header
     * @return string
     */
    public function bearerToken($header)
    {
        if(strpos($header,'Bearer ') !== false){
            return substr($header, 7);
        }
    }

    /**
     * @param string $uri
     * @param string $method
     * @param array $options
     * @param bool $returnRaw
     *
     * @return ResponseInterface|Collection|array|object|string
     * @throws GuzzleException
     */
    public function request(string $uri, string $method = 'GET', array $options = [], $returnRaw = false)
    {
        try {

            if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
                $options['base_uri'] = $this->baseUri;
            }

            if ((!empty($options['base_uri']) || $this->config->getBaseUri()) && $this->config->needAutoTrimEndpointSlash()) {
                $uri = ltrim($uri, '/');
            }
            if(!empty($this->app['config']->get('options'))){
                $options = $options?array_merge($options,$this->app['config']->get('options')):$this->app['config']->get('options');
            }

            $response = $this->performRequest($uri, $method, $options);

            return $this->castResponseToType(
                $response,
                $returnRaw ? 'raw' : $this->config->getOption('response_type')
            );

        }catch(\GuzzleHttp\Exception\ClientException $exception){

            $response = $exception->getResponse();
            return json_decode($response->getBody()->getContents(),true);

        }catch(\GuzzleHttp\Exception\ConnectException $exception){

            return ['errmsg' => '500','errmsg'=>$exception->getMessage()];
        }
    }

}